package com.ruoyi.common.utils;

import java.io.PrintWriter;
import java.io.StringWriter;
import org.apache.commons.lang3.exception.ExceptionUtils;

/**
 * 错误信息处理类。
 *
 * @author ruoyi
 */
public class ExceptionUtil
{
    /**
     * 获取exception的详细错误信息。
     */
    public static String getExceptionMessage(Throwable e)
    {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw, true));
        return sw.toString();
    }

    public static String getRootErrorMessage(Exception e)
    {
        Throwable root = ExceptionUtils.getRootCause(e);
        root = (root == null ? e : root);
        if (root == null)
        {
            return "";
        }
        String msg = root.getMessage();
        if (msg == null)
        {
            return "null";
        }
        return StringUtils.defaultString(msg);
    }

    /**
     * 限制异常链（含cause）的信息总长度
     * @param e 异常对象
     * @param maxTotalLength 最大总长度
     * @return 截断后的完整异常链信息
     */
    public static String getLimitedChainMessage(Throwable e, int maxTotalLength) {
        if (e == null) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        Throwable current = e;
        // 遍历异常链
        while (current != null) {
            String msg = current.getMessage();
            if (msg == null) {
                msg = current.getClass().getSimpleName();
            }
            sb.append(msg).append("; ");
            // 检查总长度是否超出限制
            if (sb.length() > maxTotalLength) {
                break;
            }
            current = current.getCause();
        }
        // 截断并添加标记
        String fullMsg = sb.toString();
        if (fullMsg.length() <= maxTotalLength) {
            return fullMsg;
        } else {
            return fullMsg.substring(0, maxTotalLength) + "...[异常链信息过长]";
        }
    }
}
